
import HttpHelper from './HttpHelper';
import { Base64 } from 'js-base64'
import DomHelper from './DomHelper';

const cacheKeyPrefix = 'gmCacheKey_';

export default class GmHelper {

    static init() {
        const self = this;
        self.initCacheGmResource();

        window.unsafeWindow = window;
        window.GM_getResourceText = self.getResourceText.bind(self);
        window.GM_getResourceURL = self.getResourceURL.bind(self);
        // window.GM_listValues = self.getListValues;
        // window.GM_setValue = self.setValue;
        // window.GM_getValue = self.getValue;
        // window.GM_deleteValue = self.deleteValue;
    }

    static initCacheGmResource() {
        const self = this;
        Object.keys(window.GM_Resource).forEach((key) => {
            const url = window.GM_Resource[key];
            const cacheVal = self.getValue(key);
            if (!cacheVal || cacheVal.url !== url) {
                HttpHelper.get(url)
                    .then(res => {
                        return res.text;
                    }).then(text => {
                        self.setValue(key,
                            {
                                url: url,
                                text: text
                            });
                        return text;
                    }).catch(err => {
                        console.error(err)
                    });
            }
        });
    }


    static getResourceText(name) {
        const self = this;
        const valInfo = self.getValue(name);
        return (valInfo && valInfo.text) || '';
    }

    static getResourceURL(name) {
        const self = this;
        const valInfo = self.getValue(name);
        const text = (valInfo && valInfo.text) || '';
        const base64Text = Base64.encode(text);
        const base64URL = `data:text/javascript;base64,${base64Text}`;
        return base64URL;
    }

    static getListValues() {
        const list = [];
        Object.keys(localStorage).forEach((key) => {
            if (key.startsWith(cacheKeyPrefix)) {
                list.push(JSON.parse(localStorage.getItem(key)));
            }
        });
        return list;
    }

    static setValue(name, value) {
        return localStorage.setItem(`${cacheKeyPrefix}${name}`, JSON.stringify(value));
    }

    static getValue(name) {
        return JSON.parse(localStorage.getItem(`${cacheKeyPrefix}${name}`));
    }

    static deleteValue(name) {
        return localStorage.removeItem(`${cacheKeyPrefix}${name}`);
    }
}